#!/bin/bash

# Copyright © 2020 The OpenEBS Authors
#
# This file was originally authored by Rancher Labs
# under Apache License 2018.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

source $(dirname $0)/version

cd $(dirname $0)/../package

TAG=${TAG:-${VERSION}}

# IMAGE_ORG can be used to customize the organization 
# under which images should be pushed. 
# By default the organization name is `openebs`. 
IMAGE_ORG=${IMAGE_ORG:-openebs}

BASE_DOCKER_IMAGEARM64=${BASE_DOCKER_IMAGEARM64:-arm64v8/ubuntu:18.04}
BASE_DOCKER_IMAGEPPC64LE=${BASE_DOCKER_IMAGEPPC64LE:-ubuntu:18.04}

# Specify the date of build
DBUILD_DATE=$(date +'%Y-%m-%dT%H:%M:%SZ')

# Specify the docker arg for repository url
if [ -z "${DBUILD_REPO_URL}" ]; then
  DBUILD_REPO_URL="https://github.com/openebs/jiva"
fi

# Specify the docker arg for website url
if [ -z "${DBUILD_SITE_URL}" ]; then
  DBUILD_SITE_URL="https://openebs.io"
fi

DBUILD_ARGS="--build-arg DBUILD_DATE=${DBUILD_DATE} --build-arg DBUILD_REPO_URL=${DBUILD_REPO_URL} --build-arg DBUILD_SITE_URL=${DBUILD_SITE_URL} --build-arg ARCH=${ARCH}"

if [ ! -x ../bin/longhorn ]; then
    ../scripts/build_binaries
fi

cp ../bin/longhorn* .
cp ../bin/longhorn jivactl
#cp /usr/src/tgt/pkg/tgt_*.deb .
if [ ${ARCH} == "linux_arm64" ]
then
  DOCKERFILE=Dockerfile_build_arm64
  docker build -f ${DOCKERFILE} -t ${IMAGE_ORG}/jiva-${XC_ARCH}:${TAG} ${DBUILD_ARGS} --build-arg BASE_IMAGE=${BASE_DOCKER_IMAGEARM64} .
elif [ ${ARCH} == "linux_ppc64le" ]
then
  DOCKERFILE=Dockerfile_build_ppc64le
  docker build -f ${DOCKERFILE} -t ${IMAGE_ORG}/jiva-${XC_ARCH}:${TAG} ${DBUILD_ARGS} --build-arg BASE_IMAGE=${BASE_DOCKER_IMAGEPPC64LE} .
else
  DOCKERFILE=Dockerfile_build_amd64
  docker build -f ${DOCKERFILE} -t ${IMAGE_ORG}/jiva-${XC_ARCH}:${TAG} ${DBUILD_ARGS} .
fi
echo Built ${IMAGE_ORG}/jiva-${XC_ARCH}:${TAG}
